package cn.sumpu.app.guoguojie.web.mvc.misc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.sumpu.app.guoguojie.biz.AlbumBiz;
import cn.sumpu.app.guoguojie.biz.CmsContentBiz;
import cn.sumpu.app.guoguojie.biz.DiscussBiz;
import cn.sumpu.app.guoguojie.constant.PictureType;
import cn.sumpu.app.guoguojie.domain.CmsContent;
import cn.sumpu.app.guoguojie.domain.Discuss;
import cn.sumpu.app.guoguojie.domain.DiscussTag;
import cn.sumpu.app.guoguojie.domain.DiscussTagDis;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.PageModel;
import cn.sumpu.app.guoguojie.util.PictureUrl;
import cn.sumpu.app.guoguojie.web.util.AdminUtil;
import cn.sumpu.toolkit.common.util.Common;

@Controller
public class DiscussController {
    private final static Logger logger = LoggerFactory.getLogger(DiscussController.class);

    @Autowired
    private DiscussBiz          discussBiz;
    @Autowired
    private AlbumBiz            albumBiz;
    @Autowired
    private CmsContentBiz       cmsContentBiz;

    /**
     * 运营中心查看稿件
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @throws AppBusinessException 
     */
    @RequestMapping(value = "/misc/discuss/discuss.htm")
    public String discuss(HttpServletRequest request, HttpServletResponse response) throws IOException, AppBusinessException {
        List<String> channel = new ArrayList<String>();
        //淘帮
        channel.add("77aa590e-c6e4-4183-9c09-e3a210480251");
        //0-1
        channel.add("5e02f483-87bd-4d77-81d5-a64ecdc877d0");
        //1-3   71
        channel.add("1d48a3b9-3709-4270-81b5-0267a5b3546f");
        //3-6  72
        channel.add("b22c5b02-baa2-42de-ac92-09042e8ccfa2");
        //怀孕期 73
        channel.add("c1fd788e-590b-4579-b5ef-d21a9f42c92d");
        List<DiscussTag> disTagList = discussBiz.getTagByCid(null);
        request.setAttribute("disTagList", disTagList);
        request.setAttribute("channel", channel);
        return "misc/discuss/discuss";
    }

    @RequestMapping(value = "/misc/discuss/disgrid.htm")
    public String discussGrid(Integer page, Integer pagesize, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            if (page == null) {
                page = 1;
            }
            PageModel pageModelOrder = discussBiz.getDiscussList(page, pagesize);
            pw = response.getWriter();
            pw.print(JSONObject.fromObject(pageModelOrder));
        } catch (Exception e) {
            pw = response.getWriter();
            pw.print("error");
            if (logger.isErrorEnabled()) {
                logger.error("get discussGrid failure.", e);
            }
        }
        return null;
    }

    @RequestMapping(value = "/misc/discuss/newdis.htm")
    public String newDis(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Discuss discuss = new Discuss();
        request.setAttribute("discuss", discuss);
        return "misc/discuss/newDis";
    }

    /**
     * 上图图片
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/misc/discuss/uploadImg.htm")
    public String imgUpload(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter pw = null;
        try {
            PictureUrl imageUrl = albumBiz.uploadImage(request, PictureType.DISCUSS.getValue(), false);
            pw = response.getWriter();
            pw.print(JSONObject.fromObject(imageUrl));
        } catch (Exception e) {
            e.printStackTrace();
            try {
                pw = response.getWriter();
                String outputJson = "{'err':'上传图片出错！'}";
                pw.print(JSONObject.fromObject(outputJson));
            } catch (Exception e1) {
                if (logger.isErrorEnabled()) {
                    logger.error("get discussGrid failure.", e1);
                }
            }
        }
        return null;
    }

    /**
     * 保存文稿
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/misc/discuss/savedis.htm")
    public String savedis(Discuss discuss, String picTitle, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            discuss.setCreator(AdminUtil.getUsername());
            //创建话题
            discussBiz.insertDiscuss(discuss, picTitle);
            pw = response.getWriter();
            pw.print("true");
        } catch (Exception e) {
            e.printStackTrace();
            pw = response.getWriter();
            pw.print("error");
            if (logger.isErrorEnabled()) {
                logger.error("get savedis failure.", e);
            }
        }
        return null;
    }

    /**
     * 
     * @param discuss
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/misc/discuss/updatedis.htm")
    public String updatedis(Discuss discuss, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            discussBiz.updateDiscuss(discuss);
            pw = response.getWriter();
            pw.print("true");
        } catch (Exception e) {
            pw = response.getWriter();
            pw.print("error");
            if (logger.isErrorEnabled()) {
                logger.error("get savedis failure.", e);
            }
        }
        return null;
    }

    /**
     * 推送
     * @param request
     * @param contentList
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/misc/discuss/pushdis.htm")
    public String pushdis(HttpServletRequest request, String contentList, String channel, String tagsList, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            if (Common.notEmptyStr(contentList)) {
                JSONArray contentArray = JSONArray.fromObject(contentList);
                for (Object object : contentArray) {
                    JSONObject jsonObj = JSONObject.fromObject(object);
                    //原文稿
                    Discuss discuss = (Discuss) JSONObject.toBean(jsonObj, Discuss.class);
                    CmsContent content = new CmsContent();
                    //查询发布库是否存在
                    content = cmsContentBiz.getContentByTable("discuss", discuss.getIdentifier(), channel);
                    if(!("b9a62576-070f-4c4d-8b8b-22389a8b626e").equals(channel)){
                        if(discuss.getTheme().equals("01")){
                            pw = response.getWriter();
                            pw.print("pushErorr");
                        }else if(discuss.getTheme().equals("02")){
                            if (content == null) {
                                CmsContent push = new CmsContent();
                                push.setTitle(discuss.getTitle());
                                push.setTblIdentifier(discuss.getIdentifier());
                                push.setTblName("discuss");
                                push.setChannel(channel);
                                push.setDescription(discuss.getContent());
                                push.setPicture(discuss.getTitlePic());
                                //发布库推送
                                cmsContentBiz.addCmsContent(push);
                                //标签
                                if (Common.notEmptyStr(tagsList)) {
                                    JSONArray tagsArray = JSONArray.fromObject(tagsList);
                                    for (Object objectTag : tagsArray) {
                                        JSONObject jsonTag = JSONObject.fromObject(objectTag);
                                        DiscussTagDis disTagDis = (DiscussTagDis) JSONObject.toBean(jsonTag, DiscussTagDis.class);
                                        //查询标签是否存在
                                        disTagDis.setDiscuss(discuss.getIdentifier());
                                        discussBiz.insertDiscussTagDis(disTagDis);
                                    }
                                }
                            }
                            pw = response.getWriter();
                            pw.print("true");
                        }
                    }else{
                        if (content == null) {
                            CmsContent push = new CmsContent();
                            push.setTitle(discuss.getTitle());
                            push.setTblIdentifier(discuss.getIdentifier());
                            push.setTblName("discuss");
                            push.setChannel(channel);
                            push.setDescription(discuss.getContent());
                            push.setPicture(discuss.getTitlePic());
                            //发布库推送
                            cmsContentBiz.addCmsContent(push);
                            //标签
                            if (Common.notEmptyStr(tagsList)) {
                                JSONArray tagsArray = JSONArray.fromObject(tagsList);
                                for (Object objectTag : tagsArray) {
                                    JSONObject jsonTag = JSONObject.fromObject(objectTag);
                                    DiscussTagDis disTagDis = (DiscussTagDis) JSONObject.toBean(jsonTag, DiscussTagDis.class);
                                    //查询标签是否存在
                                    disTagDis.setDiscuss(discuss.getIdentifier());
                                    discussBiz.insertDiscussTagDis(disTagDis);
                                }
                            }
                        }
                        pw = response.getWriter();
                        pw.print("true");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            pw = response.getWriter();
            pw.print("error");
            if (logger.isErrorEnabled()) {
                logger.error("get pushdis failure.", e);
            }
        }
        return null;
    }

    /**
     * 文稿详情
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/misc/discuss/discusstl.htm")
    public String discusstl(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Discuss discuss = discussBiz.getDiscussByDid(id);
            request.setAttribute("discuss", discuss);
        } catch (AppBusinessException e) {
            logger.error("discusstl", e);
        }
        return "misc/discuss/newDis";
    }

    /**
     * 文稿标签展示页面
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/misc/discuss/discusstag.htm")
    public String discusstag(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            List<String> channel = new ArrayList<String>();
            //淘帮
            //channel.add("100000069");
            //0-1   70
            channel.add("5e02f483-87bd-4d77-81d5-a64ecdc877d0");
            //1-3   71
            channel.add("1d48a3b9-3709-4270-81b5-0267a5b3546f");
            //3-6  72
            channel.add("b22c5b02-baa2-42de-ac92-09042e8ccfa2");
            //怀孕期 73
            channel.add("c1fd788e-590b-4579-b5ef-d21a9f42c92d");
            List<DiscussTag> disTagList = discussBiz.getTagByCid(null);
            request.setAttribute("disTagList", disTagList);
            request.setAttribute("channel", channel);
        } catch (AppBusinessException e) {
            logger.error("discusstag", e);
        }
        return "misc/discuss/discussTag";
    }

    @RequestMapping(value = "/misc/discuss/savaDisTag.htm")
    public String savaDisTag(DiscussTag discussTag, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            discussBiz.insertDiscussTag(discussTag);
            pw = response.getWriter();
            pw.print("true");
        } catch (Exception e) {
            pw = response.getWriter();
            pw.print("error");
            if (logger.isErrorEnabled()) {
                logger.error("get savedis failure.", e);
            }
        }
        return null;
    }

    /**
     * 删除标签
     */
    @RequestMapping(value = "/misc/discuss/deleteDisTag.htm")
    public String deleteDisTag(String tagId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            discussBiz.deleteDiscussTagById(tagId);
            pw = response.getWriter();
            pw.print("true");
        } catch (Exception e) {
            pw = response.getWriter();
            pw.print("error");
            if (logger.isErrorEnabled()) {
                logger.error("get savedis failure.", e);
            }
        }
        return null;
    }

    //
    @RequestMapping(value = "/misc/discuss/viewdistag.htm")
    public String viewDisTag(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Discuss discuss = discussBiz.getDiscussByDid(id);
            List<DiscussTagDis> dtsList = discussBiz.getDTSList(id);
            request.setAttribute("dtsList", dtsList);
            request.setAttribute("discuss", discuss);

            //
            List<String> channel = new ArrayList<String>();
            //淘帮
            //channel.add("100000069");
            //0-1   70
            channel.add("5e02f483-87bd-4d77-81d5-a64ecdc877d0");
            //1-3   71
            channel.add("1d48a3b9-3709-4270-81b5-0267a5b3546f");
            //3-6  72
            channel.add("b22c5b02-baa2-42de-ac92-09042e8ccfa2");
            //怀孕期 73
            channel.add("c1fd788e-590b-4579-b5ef-d21a9f42c92d");
            List<DiscussTag> disTagList = discussBiz.getTagByCid(null);
            request.setAttribute("disTagList", disTagList);
            request.setAttribute("channel", channel);
        } catch (AppBusinessException e) {
            logger.error("discusstl", e);
        }
        return "misc/discuss/disModTag";
    }

    //删除话题
    @RequestMapping(value = "/misc/discuss/deleteDis.htm")
    public String deleteDis(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            discussBiz.deleteDis(id);
            pw = response.getWriter();
            pw.print("true");
        } catch (Exception e) {
            pw = response.getWriter();
            pw.print("error");
            if (logger.isErrorEnabled()) {
                logger.error("get savedis failure.", e);
            }
        }
        return null;
    }

    //删除关联标签
    @RequestMapping(value = "/misc/discuss/baocunTag.htm")
    public String baocunTag(HttpServletRequest request, String did, String tagsList, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            //删除之前的标签
            discussBiz.deleteDTSById(did);
            //标签
            if (Common.notEmptyStr(tagsList)) {
                JSONArray tagsArray = JSONArray.fromObject(tagsList);
                for (Object objectTag : tagsArray) {
                    JSONObject jsonTag = JSONObject.fromObject(objectTag);
                    DiscussTagDis disTagDis = (DiscussTagDis) JSONObject.toBean(jsonTag, DiscussTagDis.class);
                    //查询标签是否存在
                    disTagDis.setDiscuss(did);
                    discussBiz.insertDiscussTagDis(disTagDis);
                }
            }
            pw = response.getWriter();
            pw.print("true");
        } catch (Exception e) {
            e.printStackTrace();
            pw = response.getWriter();
            pw.print("error");
            if (logger.isErrorEnabled()) {
                logger.error("get pushdis failure.", e);
            }
        }
        return null;
    }
}
